﻿using System;
using System.Text;
using System.Drawing;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public static partial class NativeAOT
{
    [UnmanagedCallersOnly(EntryPoint = "mtml")]
    public static unsafe double mtml(int n, IntPtr a_ptr, IntPtr b_ptr, IntPtr f_xa_n_ptr)
    {
        double* a = (double*)a_ptr.ToPointer();
        double* b = (double*)b_ptr.ToPointer();
        f_xa_n = Marshal.GetDelegateForFunctionPointer<delegatefunc_xa_n>(f_xa_n_ptr);

        return mtml(n, a, b);
    }

    /// <summary>
    /// 计算多重积分的Monte_Carlo法
    /// f计算被积函数值f(X)的函数名。
    /// </summary>
    /// <param name="n">积分重数。</param>
    /// <param name="a">a[n]各层积分的下限。</param>
    /// <param name="b">b[n]各层积分的上限。</param>
    /// <returns>函数返回积分值。</returns>
    public static unsafe double mtml(int n, double* a, double* b)
    {
        int m, i;
        double s, d;
        double* x = stackalloc double[n];

        d = 65536.0;
        s = 0.0;
        for (m = 0; m <= 65535; m++)
        {
            for (i = 0; i <= n - 1; i++)
            {
                x[i] = a[i] + (b[i] - a[i]) * rnd.NextDouble();
            }
            s = s + f_xa_n(x, n) / d;
        }
        for (i = 0; i <= n - 1; i++)
        {
            s = s * (b[i] - a[i]);
        }
        return (s);
    }

    /*
    // 计算多重积分的Monte_Carlo法例
      int main()
      { 
          double a[3]={ 1.0,1.0,1.0};
          double b[3]={ 2.0,2.0,2.0};
          double  mtmlf(int,double []);
          cout <<"s = " <<mtml(3,a,b,mtmlf) <<endl;
          return 0;
      }
    // 计算被积函数值
      double mtmlf(int n, double x[])
      { 
          int i;
          double f;
          f=0.0;
          for (i=0; i<=n-1; i++) f=f+x[i]*x[i];
          return(f);
      }
    */
}

